package org.kl.bpm.operation;

import java.util.HashMap;
import java.util.Map;

import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.task.DelegationState;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.kl.bf.web.base.BasicController;
import org.kl.bpm.cmd.CompleteTaskWithCommentCmd;
import org.kl.bpm.utils.BpmConstants;

/**
 * 完成任务
 * @author QJ
 * @date 2015年3月21日
 */
public class CompleteTaskOperation extends AbstractOperation<Void> {
	public static final String FORM_FIELD_NAME_VARIABLE = "${nodeName}";
	public static final String OPERATION_TASK_ID = "taskId";
	public static final String OPERATION_COMMENT = "完成";

	public Void execute(CommandContext commandContext) {
		ProcessEngine processEngine = getProcessEngine();
		String taskId = getParameter(OPERATION_TASK_ID);//获取任务id
		// 先设置登录用户
		IdentityService identityService = processEngine.getIdentityService();
		identityService.setAuthenticatedUserId(BasicController.getCurrentUserId());
		//获取任务
		TaskService taskService = processEngine.getTaskService();
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();//找到当前任务
		if (task == null) {
			throw new IllegalStateException("任务不存在");
		}
		if (DelegationState.PENDING == task.getDelegationState()) {
			taskService.resolveTask(taskId);
			return null;
		}
		Map<String, Object> processParameters = new HashMap<String, Object>();
		String nextAssignee = getParameter(BpmConstants.NEXT_ASSIGNEE);// 获取下一节点审批人
		if (StringUtils.isNotBlank(nextAssignee)) {
			processParameters.put(BpmConstants.NEXT_ASSIGNEE, nextAssignee);
		}
		//记录审批意见
		SetCommentOperation commentOperation = new SetCommentOperation(task,processParameters);
		commentOperation.execute(getParameters());
		processEngine.getManagementService().executeCommand(new CompleteTaskWithCommentCmd(taskId, processParameters, OPERATION_COMMENT));
		return null;
	}
}
